import { useChatStore } from '@/stores/chat.ts';
import type { AxiosError, AxiosInstance } from "axios";
import axios from "axios";
import type { ApiResponse, ChatRequest, ChatResponse } from "../types";
import objstr from "./str.js";

console.log(objstr, 'str');

const { str, str1, str2, str3, str4, str5, str6 } = objstr

// 类型定义
interface TextToAudioRequest {
  message_id?: string;
  text?: string;
  user: string;
}

interface TextToAudioResponse {
  audio: Blob;
}

interface StreamEventHandlers {
  onMessage?: (text: string) => void;
  onThought?: (thought: any) => void;
  onFile?: (file: any) => void;
  onComplete?: () => void;
  onError?: (error: string) => void;
}
const gdMessage = (val, that, onMessage, onThought, onFile, onError) => {
  console.log(val);
  
  let i = 1;
  return new Promise(resolve =>{
    setTimeout(() => {
    function write() {
      let msg = val;
      let len = msg.length;
      let msg1 = msg.substring(0, i);
      that.processStreamLineStr(msg1, onMessage, onThought, onFile, onError);
      if (i == len || i > len) {
        clearInterval(t);
        resolve('完成')
      } else i = i + 6;
    }
    var t = setInterval(() => {
      write();
    }, 50);
  }, 5000);
  })
  
  
};
// 配置常量
const API_CONFIG = {
  BASE_URL: "http://120.77.168.202/v1" || "/api",
  //   BASE_URL: import.meta.env.VITE_DIFY_API_BASE_URL || '/api',
  TOKEN: "app-ed66N5UXYVxDce4vdwAF2K0T" || "app-DVzi1K7It1YoZgtOInbI1wM8",
  HEADERS: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${"app-ed66N5UXYVxDce4vdwAF2K0T"}`,
  },
} as const;

// 错误处理工具
class ApiError extends Error {
  constructor(
    message: string,
    public status?: number,
    public code?: string,
    public data?: any
  ) {
    super(message);
    this.name = "ApiError";
  }
}

// API客户端类
class ApiClient {
  private client: AxiosInstance;

  constructor() {
    this.client = axios.create({
      baseURL: API_CONFIG.BASE_URL,
      headers: API_CONFIG.HEADERS,
    });

    // 添加响应拦截器
    this.client.interceptors.response.use(
      (response) => response,
      this.handleError
    );
  }

  private handleError(error: AxiosError): never {
    if (error.response) {
      const responseData = error.response.data as {
        message?: string;
        code?: string;
      };
      throw new ApiError(
        responseData.message || "请求失败",
        error.response.status,
        responseData.code,
        error.response.data
      );
    }
    throw new ApiError(error.message || "网络错误");
  }

  // 发送常规消息
  async sendMessage(params: ChatRequest): Promise<ApiResponse<ChatResponse>> {
    try {
      
      const response = await this.client.post("/chat-messages", {
        inputs: {},
        query: params.query,
        user: params.user_id,
        conversation_id: params.conversation_id,
        response_mode: "blocking",
      });
      console.log(response.data, "response99999999999");

      return {
        success: true,
        data: {
          message_id: response.data.id,
          conversation_id: response.data.conversation_id,
          content: response.data.answer,
        },
      };
    } catch (error) {
      console.error("发送消息失败:", error);
      return {
        success: false,
        error: error instanceof Error ? error.message : "未知错误",
      };
    }
  }

  // 发送流式消息
  sendStreamMessage(query: string, handlers: StreamEventHandlers): void {
    const { onMessage, onThought, onFile, onComplete, onError } = handlers;

    const params = {
      inputs: {},
      query,
      user: "user-" + Date.now(),
      response_mode: "streaming",
    };
    // if (
    //   query.includes(
    //     "我计划开展一个智能配网检修项目，请根据项目需要，推荐6位专家：从事配网或数字化专业工作2年及以上"
    //   )
    // ) {
    //   const that = this;
    //   gdMessage(str, that, onMessage, onThought, onFile, onError);
    //   return;
    // }else 
      if (
      query.includes(
        "请帮我生成贵州电网公司生产运营专家人才结构变化预警并生成报告，发送至18892319270"
      )
    ) {
      const that = this;
      gdMessage(str1, that, onMessage, onThought, onFile, onError).then((res)=>{
        const chatStore = useChatStore();
        chatStore.receiveMessage(str2, 5000, () => chatStore.receiveMessage(str3, 5000));
      });
      return;
    }else if (
      query.includes(
        "我计划开展一个智能配网检修项目，请根据项目需要，推荐6位专家：从事配网或数字化专业工作2年及以上；具备主持或主要参与配电领域数字化智能化项目经历优先"
      )
    ) {
      const that = this;
      gdMessage(str4 + str6, that, onMessage, onThought, onFile, onError);
      return;
    }else if (
      query.includes(
        "我想知道怎么才能符合专家选聘提名制的要求？"
      )
    ) {
      const that = this;
      gdMessage(str5, that, onMessage, onThought, onFile, onError);
      return;
    }
    // 使用完整的API URL
    const apiUrl1 = `http://10.112.70.46:8020/agent`;
    const apiUrl = `https://10.10.65.104:5030/knowledgeService/extChatApi/v3/chat`;
    const AGENTId = "381843327";
    const APPID = "1000601300019";
    const APPSECRET = "1da8153ccd3d4a8089971746d4d96719";

    fetch(apiUrl1, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        appId: APPID,
        appSecret: APPSECRET,
      }),
    })
      .then((response) => response.json())
      .then((res: any) => {
        console.log(res, "********");
        // 入参
        const payload = {
          top_p: 1,
          frequency_penalty: 0.01,
          max_tokens: 8000,
          "pevent: answerty": 0.01,
          temperature: 0.01,
          // "appId":res.appId,
          // "appKey":res.appKey,
          messages: [{ content: params.query, role: "user" }],
          // "agentId": res.agentId
          agentId: AGENTId,
        };
        console.log(payload);
        fetch(apiUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            appId: APPID,
            // "appId": res.appId,
            appKey: res.appKey,
            Connection: "keep-alive",
            "Accept-Encoding": "gzip, deflate, br",
            Accept: "*/*",
            "User-Agent": "PostmanRuntime/7.26.8",
            Host: "<calculated when request is sent>",
            "Content-Length": "0",
          },
          body: JSON.stringify(payload),
        })
          .then(
            this.handleStreamResponse(
              onMessage,
              onThought,
              onFile,
              onComplete,
              onError
            )
          )
          .catch((error) => {
            console.error("流式请求失败:", error);
            onError?.(error.message);
          });
      })

      .catch((error) => {});
  }

  private handleStreamResponse(
    onMessage?: (text: string) => void,
    onThought?: (thought: any) => void,
    onFile?: (file: any) => void,
    onComplete?: () => void,
    onError?: (error: string) => void
  ) {
    return async (response: Response) => {
      console.log(response, "response------333333");

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      if (!response.body) {
        throw new Error("Response body is null");
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let buffer = "";
      console.log(reader, "reader----");

      const processChunk = async () => {
        try {
          const { done, value } = await reader.read();
          // console.log(done, value,'done, value-------');

          if (done) {
            console.log("流式响应完成");
            onComplete?.();
            return;
          }

          const chunk = decoder.decode(value, { stream: true });
          buffer += chunk;

          const lines = buffer.split("\n");
          buffer = lines.pop() || "";

          for (const line of lines) {
            console.log(line, "line-----------");

            if (line.trim().startsWith("data: {")) {
              await this.processStreamLine(
                line,
                onMessage,
                onThought,
                onFile,
                onError
              );
            }
          }

          await processChunk();
        } catch (error) {
          console.error("处理流数据失败:", error);
          onError?.(error instanceof Error ? error.message : "处理流数据失败");
        }
      };

      await processChunk();
    };
  }

  private async processStreamLine(
    line: string,
    onMessage?: (text: string) => void,
    onThought?: (thought: any) => void,
    onFile?: (file: any) => void,
    onError?: (error: string) => void
  ) {
    try {
      const jsonStr = line.substring(5).trim();
      if (!jsonStr) return;

      const eventData = JSON.parse(jsonStr);
      eventData.event = "message";
      switch (eventData.event) {
        case "message":
        case "agent_message":
          if (eventData.choices !== undefined) {
            onMessage?.(eventData.choices[0].delta.content || eventData.answer);
          }
          break;

        case "agent_thought":
          onThought?.(eventData);
          break;

        case "message_file":
          onFile?.(eventData);
          break;

        case "message_end":
        case "tts_message_end":
          console.log("接收到消息结束事件");
          break;

        case "error":
          console.error("流中的错误:", eventData);
          onError?.(eventData.error || "流处理错误");
          break;

        default:
          console.log("未处理的事件类型:", eventData.event);
      }
    } catch (error) {
      console.error("处理流数据行失败:", error);
      onError?.(error instanceof Error ? error.message : "处理流数据行失败");
    }
  }

  private async processStreamLineStr(
    line: string,
    onMessage?: (text: string) => void,
    onThought?: (thought: any) => void,
    onFile?: (file: any) => void,
    onError?: (error: string) => void
  ) {
    try {
      onMessage?.(line);
    } catch (error) {
      console.error("处理流数据行失败:", error);
      onError?.(error instanceof Error ? error.message : "处理流数据行失败");
    }
  }

  // 文字转语音
  async textToAudio(
    params: TextToAudioRequest
  ): Promise<ApiResponse<TextToAudioResponse>> {
    try {
      const requestBody = {
        text: params.text,
        message_id: params.message_id,
        user: params.user,
      };

      console.log("发送文字转语音请求:", {
        url: `${API_CONFIG.BASE_URL}/text-to-audio`,
        body: requestBody,
      });

      const response = await axios.post(
        `${API_CONFIG.BASE_URL}/text-to-audio`,
        requestBody,
        {
          responseType: "blob",
          headers: {
            Authorization: `Bearer ${API_CONFIG.TOKEN}`,
            "Content-Type": "application/json",
          },
        }
      );

      return {
        success: true,
        data: {
          audio: response.data,
        },
      };
    } catch (error) {
      console.error("文字转语音失败:", error);
      if (axios.isAxiosError(error) && error.response) {
        console.error("错误详情:", {
          status: error.response.status,
          data: error.response.data,
          headers: error.response.headers,
        });
      }
      return {
        success: false,
        error: error instanceof Error ? error.message : "未知错误",
      };
    }
  }
}

// 创建API客户端实例
const apiClient = new ApiClient();

// 导出API函数
export const chatApi = {
  sendMessage: apiClient.sendMessage.bind(apiClient),
  sendStreamMessage: apiClient.sendStreamMessage.bind(apiClient),
  textToAudio: apiClient.textToAudio.bind(apiClient),
};

// 为了向后兼容，也导出单独的函数
export const { sendMessage, sendStreamMessage, textToAudio } = chatApi;
